<?php /* УТФ-8:fix */

class SPIcontroller__catalogs__manage extends SPIcontroller__catalogs
{
    public function gen_menu()
    {
        $menuitems = array();

        $in_topic = SPI::I('var')->get('topic');
        $in_tmode = SPI::I('var')->get('tmode');

        foreach( array( 'catalog' ) as $tmode_one )
        {
            $menuitems['MAIN'][] = array(
                'access'        => array( SPI_IAM_PERM_ADMIN ),
                'link'          => $this->pack_link( $tmode_one ),
                'icon'          => "catalogs__manage_{$tmode_one}.gif",
                'name'          => "Каталоги",
                'is_active'     => $in_topic == $this->CONTROLLER_ID && $in_tmode == $tmode_one,
                'align_prior'   => 1,
            );
        }

        return $menuitems;
    }
	
    public function pack_link( $mode = null, $vars = null, $extModule = false )
    {
		if( $extModule === false )
			return SPIc::I('manage')->link->pack( $this->CONTROLLER_ID, $mode, $vars );
		else
			return SPIc::I('manage')->link->pack( strtolower($extModule).'__manage', $mode, $vars );
    }

    public function exec( & $content )
    {
        if( SPI::I('Iam')->is_permit( SPI_IAM_PERM_ADMIN ) === true )
        {
            # access allow
        }
        else return false;

        $data = array();

        $data['topic']  = SPI::I('var')->get('topic');
        $data['tmode']  = SPI::I('var')->get('tmode');
        $data['action'] = SPI::I('var')->get('action');
        $data['pid']    = (int) SPI::I('var')->get('pid');//template

        if( in_array( $data['tmode'], array( 'catalog' ) ) === false )
        {
            return false;
        }

        switch( $data['action'] )
        {
            default:
            {
                $data['action'] = 'view';
            }
            case 'view':
            {
                if( $this->exec_view( $content, $data ) === false )
                {
                    return false;
                }
                break;
            }

            case 'insert':
            case 'modify':
            {
                $this->exec_savedata( $content, $data ); # => die by json-data response
            }

            case 'form':
            {
                if( $this->exec_form( $content, $data ) === false )
                {
                    return false;
                }
                break;
            }
        }

        $content['data'] = $data;

        return true;
    }

    private function exec_view( & $content, & $data, $is_recursive_exec = false )
    {
        if( false === ( $mCatalogs = SPIm::I('catalogs') ) )
        {
            return false;
        }
        $data['title']      = "Каталоги";
        $data['subtitle']   = "";
        $data['template']   = 'catalogs/view.tpl';

        $data['link_newitem'] = $this->pack_link( $data['tmode'], array( 'pid'=>$data['pid'], 'action'=>'form' ) );

        // --------------------------------------------------------------------

        $action_do = SPI::I('var')->get('action_do' );


        if( $is_recursive_exec === false) // if $is_recursive_exec == true --> don't need to ReExecute action
        if( in_array( $action_do, array( 'activity_on', 'activity_off', 'delete' ) ) === true )
        {
            $id_list = SPI::I('var')->get( 'multiselect' );
            
            if( is_array( $id_list ) === false )
            {
                $id_list[] = SPI::I('var')->get( 'iid' );
            }

            foreach( $id_list as $item_id )
            {
                $item_id = (int) $item_id;

                if( $item_id == 0 )
                {
                    continue;
                }

                switch( $action_do )
                {
                    case 'activity_on':  $mCatalogs->manage->set_activity( 'on', $item_id ); break;
                    case 'activity_off': $mCatalogs->manage->set_activity( 'off', $item_id ); break;
                    case 'delete':       
						$mCatalogs->manage->delete( $item_id ); 
						SPIc::I('media')->manage->delete_group( $this->MEDIA_GID, $item_id );
					break;
                }
                
            }
            unset( $id_list, $item_id );

            SPIc::I('manage')->notifier->set_message( $content, true, "Операция успешно выполнена" );
        }

        // --------------------------------------------------------------------
        // Resort list

        if( $action_do == 'resort' )
        {
            $id_list = SPI::I('var')->get( 'order_index' );
            
            if( is_array( $id_list ) === true )
            {
                foreach( $id_list as $item_id => $new_order_index_value )
                {
                    $item_id = (int) $item_id;

                    if( $item_id == 0 )
                    {
                        continue;
                    }

                    $mCatalogs->manage->set_order_index( $item_id, $new_order_index_value );
                }
                unset( $id_list, $item_id );

                SPIc::I('manage')->notifier->set_message( $content, true, "Пересортировка выполнена" );
            }
        }

        // --------------------------------------------------------------------
        // Make notifications by 'action_complite' value

        switch( SPI::I('var')->get('action_complite') )
        {
            case 'insert': SPIc::I('manage')->notifier->set_message( $content, true, "Вставка успешно выполнена" ); break;
            case 'modify': SPIc::I('manage')->notifier->set_message( $content, true, "Обновление успешно выполнено" ); break;
        }

        // --------------------------------------------------------------------
        // Build linkway from current to root

        $data['linkway'] = $this->build_linkway( $data, $data['pid'] );
        $data['catalog_level'] = count($data['linkway']);
		
        // --------------------------------------------------------------------
        // Filter objects [stdobj]

        $stdobj_baseurl = $this->pack_link( $data['tmode'], array( 'pid'=>$data['pid'], 'action'=>'view' ) );

        $content['stdobj']['f_search'] = SPIc::I('manage')->stdobj->filter(
            "{$data['topic']}:{$data['tmode']}",
            "search",
            $stdobj_baseurl
        );

        // --------------------------------------------------------------------
        // Order fields [stdobj]

        $content['stdobj']['order'] = SPIc::I('manage')->stdobj->order(
            "{$data['topic']}:{$data['tmode']}",
            $stdobj_baseurl,
            array( 'order_index+', 'name+', 'id+', 'anons+' )
        );

        // --------------------------------------------------------------------

        $qresult = $mCatalogs->manage->select(
            $data['pid'],
            $content['stdobj']['f_search']['value'],
            $content['stdobj']['order']['current']
        );

        if( $qresult === false )
        {
            return false;
        }
        
        $data['items_count'] = $qresult->num_rows();

        // --------------------------------------------------------------------
        // Pager [stdobj]

        $content['stdobj']['pager'] = SPIc::I('manage')->stdobj->pager(
            $data['topic'],
            $stdobj_baseurl,
            $data['items_count']
        );

        // --------------------------------------------------------------------
        // Generate List

        $qresult->seek( $content['stdobj']['pager']['firstitem_index'] );
        $qresult->set_manual_limit( $content['stdobj']['pager']['items_per_page'] );

        $data['items'] = array();

        while( $item = $qresult->fetch() )
        {
            $item['preview'] = SPIm::I('media')->get_public_sourceByIndexOld(
                $this->MEDIA_GID, $item['id'], 1,
                array( 'mode' => 'preview' )
            );
			
			if( $item['workstatus'] == '0' )
            {
                $item['link_activity_on'] = $this->pack_link( $data['tmode'], array( 'pid'=>$data['pid'], 'action'=>'view', 'action_do'=>'activity_on', 'iid'=>$item['id'] ) );
            }
            elseif( $item['workstatus'] == '1' ) 
            {
                $item['link_activity_off'] = $this->pack_link( $data['tmode'], array( 'pid'=>$data['pid'], 'action'=>'view', 'action_do'=>'activity_off', 'iid'=>$item['id'] ) );
            }
			
			$item['link_content'] = $this->pack_link( 'catalog', array( 'action'=>'view', 'cat'=>$item['id'] ), 'content' );
			$item['link_filters'] = $this->pack_link( 'product', array( 'action'=>'view', 'cat'=>$item['id'] ), 'filters' );
			$item['link_params']  = $this->pack_link( 'product', array( 'action'=>'view', 'cat'=>$item['id'] ), 'params' );
			
            $item['link_modify'] = $this->pack_link( $data['tmode'], array( 'pid'=>$data['pid'], 'action'=>'form', 'iid'=>$item['id'] ) );
            $item['link_delete'] = $this->pack_link( $data['tmode'], array( 'pid'=>$data['pid'], 'action'=>'view', 'action_do'=>'delete', 'iid'=>$item['id'] ) );

            if( $data['tmode'] == 'catalog' )
			{
				if( $data['catalog_level'] < 100 ) /// розрешить 1-1=0 вложеность, т.е. если поставить 3 то 3-1=2, 2-х уровневая вложеность. 
				{
					$linkway_item = $mCatalogs->manage->select( $item['id'] );

					//if($linkway_item->num_rows()>0)	// если есть вложеные каталоги 			
						$item['link_subitems'] = $this->pack_link( $data['tmode'], array( 'pid'=>$item['id'], 'action'=>'view' ) );
				
					$item['link_create_subitems'] = $this->pack_link( $data['tmode'], array( 'pid'=>$item['id'], 'action'=>'form' ) ); //link_newitem
				}
			}

            $data['items'][] = $item;
        }
        $qresult->close();

        if( count( $data['items'] ) == 0 && $data['items_count'] != 0 && $is_recursive_exec === false )
        {
            // Reset page index to number '1'
            SPIc::I('manage')->stdobj->pager_reset( "{$data['topic']}:{$data['tmode']}" );

            // Recursive run
            return $this->exec_view( $content, $data, true );
        }

        // --------------------------------------------------------------------

        $data['formvars'] = array();
        $data['formvars']['action'] = $data['action'];
        $data['formvars']['tmode']  = $data['tmode'];
        $data['formvars']['pid'] = $data['pid'];

        $data['link_form_submit'] = $this->pack_link();

        // --------------------------------------------------------------------

        return true;
    }

    private function exec_form( & $content, & $data )
    {
        if( false === ( $mCatalogs = SPIm::I('catalogs') ) )
        {
            return false;
        }

        $data['title']    = "Каталог";
        $data['subtitle'] = '';
        $data['template'] = 'catalogs/form.tpl';

        $data['link_back'] = $this->pack_link( $data['tmode'], array( 'pid'=>$data['pid'] ) );

        $item_id = (int) SPI::I('var')->get( 'iid' );

        if( $item_id )
        {
            $data['formmode'] = 'modify';
            $data['subtitle'] = "Редактирование элемента";

            $item_fields = $mCatalogs->manage->get_by_id( $item_id );
        }
        else
        {
            $data['formmode'] = 'insert';
            $data['subtitle'] = "Новый элемент";

            $item_fields = array();
        }
		
		$ext_editor = SPIc::I('widget')->spaw2->open();
        $ext_editor->addpage( 'description_ExtEditor', $item_fields['description'] );
        $item_fields['description_ExtEditor'] = $ext_editor->render();
		
        $content['item_fields'] = $item_fields;
		
        // --------------------------------------------------------------------
        // Build linkway from current to root

        $data['linkway'] = $this->build_linkway( $data, $data['pid'] );
        $data['catalog_level'] = count( $data['linkway'] );
		

        // --------------------------------------------------------------------
		
		$cMedia = SPIc::I('media');

		$content['media'] = $cMedia->manage->initialize(
			$this->MEDIA_GID,
			$item_id ? $item_id : null,
			array( $cMedia->PRESET_IMAGES ),
			array( 'limit' => 1 )
		);
		
		// -----------------------------------------------------------------------
		
        $data['formvars'] = array();
        $data['formvars']['action'] = $data['formmode'];
        $data['formvars']['tmode']  = $data['tmode'];
        $data['formvars']['pid'] = $data['pid'];

        if( $item_id )
        {
            $data['formvars']['iid'] = $item_id;
        }
		else
        {
            $data['formvars']['media_gid'] = $content['media']['gid'];
        }
		
        $data['link_form_submit'] = $this->pack_link();

        // --------------------------------------------------------------------

        return true;
    }

    private function exec_savedata( & $content, & $data )
    {
        if( false === ( $mCatalogs = SPIm::I('catalogs') ) )
        {
            return false;
        }

        if( in_array( $data['action'], array( 'insert', 'modify' ) ) === false )
        {
            trigger_error( 'Undefined action ('.$data['action'].')', E_USER_ERROR );
        }

        // --------------------------------------------------------------------

        if( $data['action'] == 'insert' )
        {
            $item_id = null;
        }
        else # modify
        {
            $item_id = (int) SPI::I('var')->get('iid');
        }

        $in_values = SPI::I('var')->get('field');
		$target = $in_values['target'];
        // --------------------------------------------------------------------

        $validator = SPIc::I('validator')->open();

        $validator->add_rule( 'workstatus',     'integer[0:1]' );
        $validator->add_rule( 'name',           'string[1:64]' );
		$validator->add_rule( 'anons',          'string' );
        $validator->add_rule( 'description',    'string:ExtEditorClean' );
		if($in_values['link'])
			$validator->add_rule( 'link',       'url' );
		if($in_values['target'])
			$validator->add_rule( 'target',       'integer[0:1]' );
        
		list( $status, $validator_data ) = $validator->exec( $in_values );

        if( $status === false )
        {
            $response = array();
            $response['status'] = 'error';
            $response['error_messages'] = $validator_data; // as errors
            SPIv::I('json')->render($response);
            die();
        }

        // --------------------------------------------------------------------
        // Pre insert | modify actions

        $in_values = $validator_data; // as parsed values
		
        if( $data['action'] == 'insert' )
        {
            switch( SPI::I('var')->get('order_position') )
            {
                case 'first':
                {
                    $in_values['order_index'] = $mCatalogs->manage->get_order_value( $data['pid'], 'min') - 10;
                    break;
                }
                
                case 'last':
                {
                    $in_values['order_index'] = $mCatalogs->manage->get_order_value( $data['pid'], 'max') + 10;
                    break;
                }
            }
        }

        // --------------------------------------------------------------------
        // Do insert | modify
		$in_values['target'] = $target;	
		if( empty($in_values['link']) )
		{
			$in_values['link']=null;
			$in_values['target']=null;
		}
		
        if( $data['action'] == 'insert' )
        {
            $in_values['pid'] = $data['pid'];
			
            $status = $mCatalogs->manage->insert( $in_values );

            if( $status !== false )
            {
                $item_id = $status;
                $status = true;
            }
        }
        else # modify
        {
            $status = $mCatalogs->manage->modify( $item_id, $in_values );
        }

        // --------------------------------------------------------------------

        if( $status === false )
        {
            $response = array();
            $response['status'] = 'error_alert';

            if( $data['action'] == 'insert' )
            {
                $response['error_message'] = 'При вставке данных возникла ошибка!';
            }
            else
            {
                $response['error_message'] = 'При сохранении данных возникла ошибка!';
            }

            SPIv::I('json')->render($response);
            die();
        }

        // --------------------------------------------------------------------
        // Post insert | modify actions

        if( $status === true && $data['action'] == 'insert' )
        {
            SPIc::I('media')->manage->attach_pack_for_newitem(
                SPI::I('var')->get('media_gid'),
                $item_id
            );
        }

        // --------------------------------------------------------------------

        $response = array();
        $response['status'] = 'complite';
        $response['link_redirect'] = $this->pack_link( $data['tmode'], array( 'pid'=>$data['pid'], 'action'=>'view', 'action_complite' => $data['action'] ) );
        SPIv::I('json')->render($response);
        die();
    }

    public function build_linkway( & $data, $item_id )
    {
        if( false === ( $mCatalogs = SPIm::I('catalogs') ) )
        {
            return false;
        }

        $linkway = array();

        $index = 100; // max catalog level
        while( $index-- >= 0 && $item_id != 0 )
        {
            $linkway_item = $mCatalogs->manage->get_by_id( $item_id );
            $linkway_item['link'] = $this->pack_link( $data['tmode'], array( 'pid'=>$linkway_item['id'], 'action'=>'view' ) );

            $linkway[] = $linkway_item;

            $item_id = $linkway_item['pid'];
        }

        if( $index == 0 )
        {
            $linkway = array(); // reset
        }

        $linkway[] = array(
            'id' => null,
            'name' => 'Главные подразделы',
            'link' => $this->pack_link( $data['tmode'], array( 'action'=>'view' ) )
        );
		
        return array_reverse( $linkway );
    }
	
	
	public function build_tree( & $tree, $pid = null, $a=0)
	{	
		$qresult = SPIm::I('catalogs')->manage->select( $pid );
		
		if($qresult->num_rows()>0){
			$a++;
			while( $i = $qresult->fetch() )
			{	
				for($b=1;$b<$a;$b++){
					$i['name']='-----'.$i['name'];
				}
				$i['vlog'] = $a;
				$tree[] = $i;
				$this-> build_tree($tree,$i['id'], $a);
			}
			$qresult->close();
		}
		else{
			$a--;
			return $tree;
		}
	}
	
	public function get_pid_catalog($id){
		$item = SPIm::I('catalogs')->manage->get_by_id($id);
		return $item['pid'];
	}
	
	public function get_fuul_way_catalog(& $data, $id){
		$catalog = SPIc::I('catalogs')->manage->build_linkway( & $data, $id );
		$count = 1;
		foreach($catalog as $value){
			if($count == 1){}
			elseif($count == 2 ){
				$full_way = $value['name'];
			}
			else
			$full_way = $full_way."/".$value['name'];
			$count++;
		}
		return $full_way;
	}
	
	public function getCatalogsTree( $item_id )
    {
        $list = array();

        $index = 100; // max catalog level
        while( $index-- >= 0 && $item_id != 0 )
        {
            $item = SPIm::I('catalogs')->manage->get_by_id( $item_id );

            $list[] = $item['id'];

            $item_id = $item['pid'];
        }
		
        return $list;
    }
}
